package com.cty.servlet.servlet8.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Auther: cty
 * @Date: 2020/2/16 16:59
 * @Description:
 * @version: 1.0
 */
@WebFilter(filterName = "MyFilter02")
public class MyFilter02 implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("MyFilter02.doFilter(我是第二个过滤器：浏览器——>服务器拦截)");
        //判断session
        HttpSession hs=((HttpServletRequest) req).getSession();
        if(hs.getAttribute("uname")==null){
            Object uname = ((HttpServletRequest) req).getParameter("uname");
            if(uname!=null){  //若request中uname不为空，则向session中添加uname，并放行
                hs.setAttribute("uname", uname);
                chain.doFilter(req, resp);
                System.out.println("MyFilter02.doFilter(我是第二个过滤器：服务器——>浏览器拦截)");
            }else{  //若session和request中uname都为空，则重定向登录页面
                ((HttpServletResponse)resp).sendRedirect("login.jsp");
            }
        }else{
            //放行
            chain.doFilter(req, resp);
            System.out.println("MyFilter02.doFilter(我是第二个过滤器：服务器——>浏览器拦截)");
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
